package com.wfl.sampling.service.impl;

import com.wfl.sampling.dao.UserParticipationDao;
import com.wfl.sampling.entity.Activity;
import com.wfl.sampling.entity.UserParticipation;
import com.wfl.sampling.service.ActivityService;
import com.wfl.sampling.service.UserParticipationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gefangjie
 */
@Service
public class UserParticipationServiceImpl implements UserParticipationService {
    @Autowired
    private UserParticipationDao userParticipationDao;
    @Autowired
    private ActivityService activityService;
    //添加参与活动
    @Override
    public void addParticipation(int userId, int activityId) {
        userParticipationDao.addParticipation(userId, activityId);
    }
    //取消参与活动
    @Override
    public void deleteParticipation(int userId, int activityId) {
        userParticipationDao.deleteParticipation(userId, activityId);
    }
    //检查是否参与活动
    @Override
    public boolean checkParticipation(int userId, int activityId) {
        return userParticipationDao.checkParticipation(userId, activityId);
    }
    //更新支付状态
    @Override
    public void updatePaymentStatus(int userId, int activityId) {
        userParticipationDao.updatePaymentStatus(userId, activityId);
    }
    //通过用户id查询参与活动
    @Override
    public List<Activity> queryUpByUserId(int userId) {
        List<UserParticipation> result = userParticipationDao.queryUpByUserId(userId);
        if (result.isEmpty()) {
            return Collections.emptyList();
            // 如果用户没有参与任何活动，直接返回空列表
        }
        List<Activity> activities = new ArrayList<>();
        // 为了减少数据库访问次数，可以将所有活动ID收集起来，一次性查询
        List<Integer> activityIds = result.stream()
                .map(UserParticipation::getActivityId)
                .distinct()
                .collect(Collectors.toList());
        // 收集所有唯一的活动ID
        return activityService.findActivitiesByActivityIds(activityIds);
    }

}
